import React from "react";
import {
  Input,
  InputGroup,
  Stack,
  InputLeftAddon,
  InputRightAddon,
  FormHelperText,
  Button,
  FormControl,
  Flex,
  useToast,
} from "@chakra-ui/core";
import { Field, Form, Formik } from "formik";
import { FaUserAlt, FaLock, FaCheck } from "react-icons/fa";
import request from "../request";

export default function SignIn() {
  const toast = useToast();
  function validate(value) {
    let error;
    if (!value) {
      error = "此项为必填项";
    }
    return error;
  }

  return (
    <Formik
      initialValues={{
        email: "337829740@qq.com",
        password: "12345678",
      }}
      onSubmit={async (values) => {
        try {
          await request("/login", { user: values });
          toast({
            position: "top",
            title: "Sign in success.",
            status: "success",
          });
        } catch (error) {
          toast({
            position: "top",
            title: "Not sign in.",
            description: JSON.stringify(error),
            status: "error",
          });
        }
      }}
    >
      {(props) => (
        <Form>
          <Stack spacing="2">
            <Field name="email" validate={validate}>
              {({ field, form }) => (
                <FormControl isInvalid={form.errors.email && form.touched.email}>
                  <InputGroup>
                    <InputLeftAddon children={<FaUserAlt />} />
                    <Input {...field} placeholder="请输入邮箱或手机号" />
                  </InputGroup>
                  {form.touched.email && <FormHelperText>{form.errors.email}</FormHelperText>}
                </FormControl>
              )}
            </Field>
            <Field name="password" validate={validate}>
              {({ field, form }) => (
                <FormControl isInvalid={form.errors.password && form.touched.password}>
                  <InputGroup>
                    <InputLeftAddon children={<FaLock />} />
                    <Input
                      {...field}
                      type="password"
                      placeholder="请输入密码"
                    />
                    <InputRightAddon children={<FaCheck />} />
                  </InputGroup>
                  {form.touched.password && <FormHelperText>{form.errors.password}</FormHelperText>}
                </FormControl>
              )}
            </Field>
            <Flex w="100%" justifyContent="center">
              <Button
                _hover={{ bgColor: "tomato" }}
                w="100%"
                colorScheme="teal"
                type="submit"
              >
                登录
              </Button>
            </Flex>
          </Stack>
        </Form>
      )}
    </Formik>
  );
}
